package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.vo.LoginSuccessRespVo;
import com.atguigu.gmall.user.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/api/user")
public class UserApicontroller {

    @Autowired
    UserInfoService userInfoService;

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @PostMapping("/passport/login")
    public Result login(@RequestBody LoginVo loginVo,HttpServletRequest request) {

        LoginSuccessRespVo respVo = userInfoService.login(loginVo,request);
        //需要返回 {token  令牌, userinfo}

        if (respVo == null) {
            return Result.build("null", ResultCodeEnum.LOGIN_INVAID);
        }
        return Result.ok(respVo);
    }

    //http://api.gmall.com/api/user/passport/logout

    /**
     * 退出  一般token会在Authorization头上
     *
     * @param token
     * @return
     */
    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader("token") String token, HttpServletResponse response){

        userInfoService.loginOut(token);
     /*   //前端不删,后端也可以自己删除  ,添加一个同名cookie
        Cookie cookie = new Cookie("name","");
        cookie.setMaxAge(0);  //0 为立即删除
        response.addCookie(cookie);*/

        return Result.ok();//给前端返回ok,前端会自己删cookie
    }
}
